using System;
using full_leaf_framework.Visual;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace touhou_bullet_rain;

// 道具
public class Item {

    public Drawable selfDrawable;

    public string uuid;
    public Vector2 pos;
    private Vector2 posCorrectSwift;
    public Vector2 velocity = Vector2.Zero;

    public Item(string uuid, Vector2 pos, Vector2 velocity) {
        this.uuid = uuid;
        this.pos = pos;
        posCorrectSwift = Vector2.Zero;
        this.velocity = velocity;
        try {
            var sprite = new AnimatedSprite(GameManager.Content.Load<Texture2D>("Projectile/item"));
            selfDrawable = new Drawable(sprite, pos, Vector2.Zero);
        }
        catch { selfDrawable = null; }
    }

    public void HandleServerRequest(string[] paramsList) {
        if (!(paramsList[0].ToString() == uuid)) { return; }
        try {
            posCorrectSwift = new Vector2(float.Parse(paramsList[1]),
                float.Parse(paramsList[2])) - pos;
            velocity = new Vector2(float.Parse(paramsList[3]),
                float.Parse(paramsList[4]));
        }
        catch (Exception e) {
            Console.WriteLine("Error When Handle Request -> " + e);
        }
    }

    public void Update(GameTime gameTime) {
        // 处理本地的一些更新，例如计算角度，速度
        pos += (float)gameTime.ElapsedGameTime.TotalSeconds * velocity;
        CorrectCurrPos(gameTime);
        selfDrawable.pos = pos;
        selfDrawable.angle += (float)gameTime.ElapsedGameTime.TotalSeconds * MathF.PI / 6;
    }

    private void CorrectCurrPos(GameTime gameTime) {
        float distance = posCorrectSwift.Length();
        float approachVelocity = 30f + distance * 1.5f + distance * distance * 0.5f;
        approachVelocity *= (float)gameTime.ElapsedGameTime.TotalSeconds;
        if (distance <= approachVelocity) {
            pos += posCorrectSwift;
            posCorrectSwift = Vector2.Zero;
        }
        else {
            Vector2 currSwift = posCorrectSwift;
            currSwift.Normalize(); currSwift *= approachVelocity;
            pos += currSwift;
            posCorrectSwift -= currSwift;
        }
    }

    public void Draw(Camera camera) {
        if (selfDrawable is not null) { camera.insertObject(selfDrawable); }
    }

}